import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import '../../../gen/assets.gen.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/ring_service.dart';
import 'year_calendar_view.dart';

/// 日历类型枚举
enum CalendarType {
  sleep, // 睡眠
  bloodOxygen, // 血氧
  pressure, // 压力
  hrv, // 心率变异性
  heartRate, // 心率
  activity, // 活动
  food, // 饮食
  eventSubtotal, // 事件小计
}

/// 简洁日历页面
class SimpleCalendarView extends StatefulWidget {
  final CalendarType calendarType;

  const SimpleCalendarView({
    super.key,
    required this.calendarType,
  });

  @override
  State<SimpleCalendarView> createState() => _SimpleCalendarViewState();
}

class _SimpleCalendarViewState extends State<SimpleCalendarView> {
  DateTime _currentDate = DateTime.now();
  Set<String> _dataDateSet = {}; // 存储有数据的日期字符串
  bool _isLoading = false;
  late final RingService _ringService;

  @override
  void initState() {
    super.initState();
    _ringService = Get.find<RingService>();
    _loadCalendarData();
  }

  /// 根据日历类型加载对应的数据
  Future<void> _loadCalendarData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final deviceSn = _ringService.getCurrentDeviceSn();
      dynamic response;

      // 根据日历类型调用不同的接口
      switch (widget.calendarType) {
        case CalendarType.sleep:
          response = await DefaultApi().querySleepCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.bloodOxygen:
          response =
              await DefaultApi().queryBloodOxygenCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.pressure:
          response = await DefaultApi().queryPressureCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.hrv:
          response = await DefaultApi().queryHrvCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.heartRate:
          response = await DefaultApi().queryHeartRateCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.activity:
          response = await DefaultApi().queryActivityCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.food:
          response = await DefaultApi().queryFoodCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
        case CalendarType.eventSubtotal:
          response = await DefaultApi().queryEventSubtotalCalendarListGet<dynamic>(
            deviceSn: deviceSn,
            isShowLoading: false,
          );
          break;
      }

      if (response != null && response is Map && response['data'] != null) {
        final List<dynamic> dataList = response['data'] as List<dynamic>;
        final Set<String> tempSet = {};

        for (var item in dataList) {
          if (item is Map<String, dynamic>) {
            final dailyValue = item['dailyValue'] as String?;
            if (dailyValue != null) {
              tempSet.add(dailyValue);
            }
          }
        }

        setState(() {
          _dataDateSet = tempSet;
        });
      }
    } catch (e) {
      print('加载日历数据失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 顶部渐变背景
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: 300.h,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topRight,
                  end: Alignment.bottomRight,
                  colors: ThemeManager.to.backgroundGradientColors,
                  stops: const [0.1, 0.3, 0.7, 1.0],
                ),
              ),
            ),
          ),
          // 内容区域
          SafeArea(
            child: Column(
              children: [
                // 自定义AppBar
                _buildCustomAppBar(),
                // 日历内容
                Expanded(
                  child: Container(
                    margin: EdgeInsets.all(11.w),
                    decoration: BoxDecoration(
                      border:
                          Border.all(width: 1, color: const Color(0xff212121)),
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child: Column(
                      children: [
                        // 星期标题
                        Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 16.w, vertical: 10.h),
                          child: Row(
                            children: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                                .map((day) => Expanded(
                                      child: Center(
                                        child: Text(
                                          day,
                                          style: TextStyle(
                                            color:
                                                Colors.white.withOpacity(0.7),
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                    ))
                                .toList(),
                          ),
                        ),
                        // 日历网格
                        Expanded(
                          child: _isLoading
                              ? const Center(
                                  child: CircularProgressIndicator(
                                    color: Color(0xffF46425),
                                  ),
                                )
                              : _buildCalendarGrid(),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建自定义AppBar
  Widget _buildCustomAppBar() {
    return Container(
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 返回按钮
          IconButton(
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 20,
            ),
            onPressed: () => Get.back(),
          ),
          // 中间标题区域
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 左侧月份导航按钮
                IconButton(
                  onPressed: _previousMonth,
                  icon: Assets.status.preMonth.image(
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
                SizedBox(width: 16.w),
                // 中间年份月份显示
                Text(
                  '${_currentDate.year}年${_currentDate.month}月',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                SizedBox(width: 16.w),
                // 右侧月份导航按钮
                IconButton(
                  onPressed: _nextMonth,
                  icon: Assets.status.nextMonth.image(
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
              ],
            ),
          ),
          // 右侧日历图标
          GestureDetector(
            onTap: _onYearCalendarTap,
            child: Assets.status.yearCalendar.image(
              width: 24.w,
              height: 24.w,
              color: const Color(0xffF46425),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCalendarGrid() {
    final firstDayOfMonth = DateTime(_currentDate.year, _currentDate.month, 1);
    final lastDayOfMonth =
        DateTime(_currentDate.year, _currentDate.month + 1, 0);
    final firstWeekday = firstDayOfMonth.weekday; // 1=周一, 7=周日
    final daysInMonth = lastDayOfMonth.day;

    // 创建日历网格数据
    final List<DateTime?> dates = [];

    // 添加空白占位符（当月第一天之前的空位）
    for (int i = 1; i < firstWeekday; i++) {
      dates.add(null);
    }

    // 添加当月的日期
    for (int i = 1; i <= daysInMonth; i++) {
      dates.add(DateTime(_currentDate.year, _currentDate.month, i));
    }

    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 7,
        childAspectRatio: 1.0,
        crossAxisSpacing: 4.w,
        mainAxisSpacing: 6.h,
      ),
      itemCount: dates.length,
      itemBuilder: (context, index) {
        final date = dates[index];

        // 如果是空白占位符，返回空容器
        if (date == null) {
          return Container();
        }

        final isToday = _isToday(date);
        final hasData = _hasData(date);

        return GestureDetector(
          onTap: hasData ? () => _onDateTap(date) : null,
          child: Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: hasData ? const Color(0xffF46425) : Colors.transparent,
              border: isToday
                  ? Border.all(color: const Color(0xffF46425), width: 2)
                  : null,
            ),
            child: Center(
              child: Text(
                date.day.toString(),
                style: TextStyle(
                  color: hasData ? Colors.white : Colors.white.withOpacity(0.7),
                  fontSize: 14.sp,
                  fontWeight: hasData ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  void _previousMonth() {
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month - 1);
    });
    _loadCalendarData(); // 重新加载数据
  }

  void _nextMonth() {
    setState(() {
      _currentDate = DateTime(_currentDate.year, _currentDate.month + 1);
    });
    _loadCalendarData(); // 重新加载数据
  }

  void _onDateTap(DateTime date) {
    // 点击有数据的日期，返回到上一级页面并传递选中的日期
    final dateStr =
        '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    Get.back(result: dateStr);
  }

  void _onYearCalendarTap() async {
    // 跳转到整年日历页面
    final result = await Get.to(() => const YearCalendarView());
    if (result != null && result is DateTime) {
      // 如果从整年日历返回了选中的月份，更新当前日期
      setState(() {
        _currentDate = result;
      });
      _loadCalendarData(); // 重新加载数据
    }
  }

  bool _isToday(DateTime date) {
    final now = DateTime.now();
    return date.year == now.year &&
        date.month == now.month &&
        date.day == now.day;
  }

  /// 检查指定日期是否有数据
  bool _hasData(DateTime date) {
    final dateStr =
        '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    return _dataDateSet.contains(dateStr);
  }
}
